import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class ParkingLot {

    private int parkingSpaceNum;        // 车位数量
    private Map<Integer, Car> hashMap = new HashMap<>();
    private static int count = 0;

    public ParkingLot(int parkingSpaceNum) {
        this.parkingSpaceNum = parkingSpaceNum;
        for (int i = 0; i < parkingSpaceNum; i++) {
            hashMap.put(i, null);
        }
    }

    // 车辆入库
    public void carIn(Car car) {
        if (count == parkingSpaceNum) {
            System.out.println("停车场车位已满！");
        } else {
            Set<Map.Entry<Integer, Car>> entries = hashMap.entrySet();
            for (Map.Entry<Integer, Car> entry : entries) {
                if (entry.getValue() == null) {
                    hashMap.put(entry.getKey(), car);
                    count++;
                    break;
                }
            }
        }
    }

    // 车辆出库
    public void carOut(Car car) {
//        if (count < 0) {
//            System.out.println("停车场车位已空！");
//        } else {
        Set<Map.Entry<Integer, Car>> entries = hashMap.entrySet();
        for (Map.Entry<Integer, Car> entry : entries) {
            if (entry.getValue() == car) {
                hashMap.put(entry.getKey(), null);
                count--;
                break;
            }
        }
//        }
    }

    // 查询当前停车场的剩余车位
    public int parkingSpaceNumLeft() {
        return parkingSpaceNum - count;
    }

    // 根据车牌号查询汽车对象的方法(返回停车位编号 -1表示没找到)
    public int inquireCar(Car car) {
        Set<Map.Entry<Integer, Car>> entries = hashMap.entrySet();
        for (Map.Entry<Integer, Car> entry : entries) {
            if (entry.getValue() == car) {
                return entry.getKey();
            }
        }
        return -1;
    }

    // 给定一个车位编号，查询这个车位编号是否停车
    public boolean isParking(int number) {
        Set<Map.Entry<Integer, Car>> entries = hashMap.entrySet();
        for (Map.Entry<Integer, Car> entry : entries) {
            if (entry.getKey() == number || entry.getValue() != null) {
                return true;
            }
        }
        return false;
    }

    public void printInfo() {
        Set<Map.Entry<Integer, Car>> entries = hashMap.entrySet();
        for (Map.Entry<Integer, Car> entry : entries) {
            if (entry.getValue() != null) {
                System.out.println("车位" + (entry.getKey() + 1) + "：牌照" + entry.getValue().getCarNumber() + " 停车时长 " + ((System.currentTimeMillis() - entry.getValue().getParkingStartTime()) /1000.0) + "秒");
            } else {
                System.out.println("车位" + (entry.getKey() + 1) + "：空");
            }
        }
    }

}
